package cn.itcast.web.controller.system;

import cn.hutool.core.util.StrUtil;
import cn.itcast.domain.system.Dept;
import cn.itcast.domain.system.Role;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.DeptService;
import cn.itcast.service.system.RoleService;
import cn.itcast.service.system.UserService;
import cn.itcast.util.ImageUploadUtils;
import cn.itcast.util.JedisUtils;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/system/user", name = "用户模块")
public class UserController extends BaseController {
    @Reference
    private UserService userService;
    @Reference
    private DeptService deptService;
    @Reference
    private RoleService roleService;

    @RequestMapping(value = "/changeRole",name = "实现用户分配角色")
    public  String changeRole(String userId, String[] roleIds){
        userService.changeRole(userId, roleIds);
        return "redirect:/system/user/list.do";
    }


    @RequestMapping(value = "/roleList", name = "进入角色分配页面")
    public String roleList(String id) {
        User user = userService.findById(id);
        request.setAttribute("user",user);

        List<Role> roleList = roleService.findAll(getCompanyId());
        request.setAttribute("roleList",roleList);

        List<String> roleIdList = userService.findRoleIdListByUserId(id);
        String userRoleStr = "";
        for (String roleId : roleIdList) {
            userRoleStr += roleId + ",";//字符串拼接
        }
        request.setAttribute("userRoleStr",userRoleStr);
        return "system/user/user-role";

    }

    @RequestMapping(value = "/list",name = "分页查询")
    @RequiresPermissions("用户管理")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize){
        PageInfo page = userService.findByPage(pageNum, pageSize, getCompanyId());
        request.setAttribute("page", page);
        return "system/user/user-list";
    }

    @RequestMapping(value = "/toAdd", name = "新增页面")
    public String toAdd() {
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList", deptList);
        return "system/user/user-add";
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @RequestMapping(value = "/edit", name = "新增/修改")
    public String edit(User user) throws InterruptedException {

        String to = user.getEmail();
        String title = "Export货代云平台-" + getCompanyName();
        String content = StrUtil.format("{},恭喜您注册成功... <br>访问网址：http://localhost:8888<br>登录邮箱:{},密码：{}", user.getUserName(), user.getEmail(), user.getPassword());
        // 封装到map集合
        Map map = new HashedMap();
        map.put("to", to);
        map.put("title", title);
        map.put("content", content);


        // 对密码进行加盐加密
        if (StrUtil.isNotEmpty(user.getPassword())) {
            Md5Hash md5Pwd = new Md5Hash(user.getPassword(), user.getEmail(), 2);
            user.setPassword(md5Pwd.toString());
        }

        // 判断用户id是否存在
        if (StrUtil.hasEmpty(user.getId())) {
            // 指定所属企业id和企业名称
            user.setCompanyId(getCompanyId());
            user.setCompanyName(getCompanyName());
            userService.save(user);
            // 发送邮件
           // MailUtil.sendMail(to, title, content);
            amqpTemplate.convertAndSend("mail.register", map);


        } else {
            userService.update(user);
        }

        return "redirect:/system/user/list.do";
    }
    @RequestMapping(value = "/toUpdate",name = "修改页面")
    public String toUpdate(String id){
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList", deptList);
        User user = userService.findById(id);
        user.setPassword(null);//防止密码重复更改
        request.setAttribute("user", user);

        return "system/user/user-update";
    }


    @RequestMapping(value = "/delete",name = "删除")
    public String delete(String id){
        userService.delete(id);
        return "redirect:/system/user/list.do";
    }
    @RequestMapping(value = "/myMessage",name = "我的信息")
    public String myMessage(){
        User loginUser = getLoginUser();
        loginUser.setPassword(null);
        request.setAttribute("user", loginUser);
        return "system/user/user-my";
    }

    @RequestMapping(value = "/updateInfo", name = "头像上传,密码修改")
    public String updateInfo(User user, MultipartFile userImg)throws Exception {

        // 图片上传 start
        // 非空判断
        if(userImg!=null && !userImg.isEmpty()){
            // 调用七牛云工具类实现文件上传
            String imgUrl = ImageUploadUtils.upload(userImg.getInputStream());
            user.setImg(imgUrl);
        }
        //加盐加密
        if (StrUtil.isNotEmpty(user.getPassword())) {
            Md5Hash md5Pwd = new Md5Hash(user.getPassword(), user.getEmail(), 2);
            user.setPassword(md5Pwd.toString());
        }
        userService.update(user);
        return "redirect:/login.do";
    }


    }
